-- Copyright (c) 2016 Lucky Byte, Inc.
--
-- Summary : 导入银联非标卡 BIN 数据
--
-- Author : xiaohu <xiaohu@lucky-byte.com>
-- Since  : 2016.8.3
--
-- Reference
--  006.3 - 中国银联银行卡系统技术规范 第三部分 文件接口规范
--
-- History
--  2016.08.03 : 建立此文件
--
local _load_file = require 'upay.dbload.loadfile'

-- 解析单行数据, 以 table 返回解析后的数据，或 nil
--
local _split_non_line = function(filepath, line_num, line)
    if string.len(line) < 147 then
        logger.warn('NONBIN 文件[%s]第[%s]行数据[%s]长度[%d]不足147，忽略之.',
            filepath, line_num, line, string.len(line))
        return nil
    end
    return {
        card_type           = 1,
        issuer_code         = string.trim(string.sub(line, 1, 11)),
        issuer_name         = string.trim(gb18030.str(string.sub(line, 13, 42))),
        card_name           = string.trim(gb18030.str(string.sub(line, 44, 63))),
        card_no_track       = string.trim(string.sub(line, 65, 67)),
        card_no_start_pos   = string.trim(string.sub(line, 69, 70)),
        card_no_len         = string.trim(string.sub(line, 72, 73)),
        bin_num             = string.trim(string.sub(line, 75, 86)),
        bin_track           = string.trim(string.sub(line, 88, 90)),
        bin_start_pos       = string.trim(string.sub(line, 92, 93)),
        bin_len             = string.trim(string.sub(line, 95, 96)),
        all_track           = string.trim(string.sub(line, 98, 100)),
        all_track_start_pos = string.trim(string.sub(line, 102, 103)),
        all_track_len       = string.trim(string.sub(line, 105, 110)),
        cup_logo_flag       = string.trim(string.sub(line, 112, 112)),
        debit_credit_flag   = string.trim(string.sub(line, 114, 114)),
        usage_index         = 0,
        add_delete_stat     = string.trim(string.sub(line, 116, 116)),
        additional_data     = string.trim(string.sub(line, 118, 147)),
    }
end

-- 入口函数
--
local _load_nonbin = function(filepath)
    return _load_file({
        filepath    = filepath,
        table_name  = 'pay_cardbin',
        line_split  = _split_non_line,
        unique_keys = { 'card_type', 'bin_num', 'bin_len', 'card_no_len' }
    })
end

return _load_nonbin
